package com.algorithm.queue;/*
 *@Author:DOWN
 *@Date:2021/12/29 10:53
 *@Comment:
 */

import com.algorithm.link.LinkedList;

public class LinkedRealizeQueue<E> implements QueueInterface<E>{

    /**
     * 私有节点类
     */
    private class Node {
        //元素
        public E item;
        //下级
        public LinkedRealizeQueue.Node next;

        public Node(E newItem, LinkedRealizeQueue.Node newNext) {
            this.item = newItem;
            this.next = newNext;
        }

        public Node(E newItem) {
            this(newItem, null);
        }

        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return item.toString();
        }
    }
    private Node head;
    private Node tail;
    private int size;
    public LinkedRealizeQueue(){
        head=null;
        tail=null;
        size=0;
    }
    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public void enqueue(E item) {
        if(tail==null){
            tail=new Node(item);
            head=tail;
        }else {
            tail.next=new Node(item);
            tail=tail.next;
        }
        size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Add failed. Illegal index.");
        }
        Node del=head;
        head=head.next;
        del.next=null;
        if(head==null){
            tail=null;
        }
        size--;
        return del.item;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Add failed. Illegal index.");
        }
        return head.item;
    }
    @Override
    public String toString() {
        if (isEmpty()) {
            return "[]";
        }
        StringBuilder str = new StringBuilder();
        str.append("[");
        Node prev = head;
        for (int i = 0; i < size; i++) {
            str.append(prev.toString());
            if (prev.next == null) {
                str.append("]");
            } else {
                str.append("->");
            }
            prev = prev.next;
        }
        return str.toString();
    }
    /**
     * 测试用例
     *
     * @param arrgs 字符串
     */
    public static void main(String[] arrgs) {
        LinkedRealizeQueue<Integer> list = new LinkedRealizeQueue<>();
        for (int i = 0; i < 10; i++) {
            list.enqueue(i);
            System.out.println(list.toString());
        }
        list.dequeue();
        System.out.println(list.toString());
    }
}
